# Icecast communication interface.

import urllib2
from django.conf import settings

ICECAST_URL = 'http://%s:%d/status_streamux.xsl'

def metadata():
    try:
        res = urllib2.urlopen(ICECAST_URL % (settings.ICECAST_HOST,
                                             settings.ICECAST_PORT))
    except urllib2.URLError:
        return None
    if not res:
        return None
    data = res.read().strip()
    res.close()

    blocks = [x.strip() for x in data.split('END') if x.strip()]
    stats = {}
    for block in blocks:
        d = dict(x.split('=', 1) for x in block.split('\n'))
        mount = d['mount'].split('.', 1)[1]
        stats[mount] = { 'listeners': d['listeners'],
                         'current': d['current'] }

    # Hack: icecast messes up the data for the mp3 stream, clean it up.
    if 'mp3' in stats and stats['mp3']['current'].startswith(' - '):
        stats['mp3']['current'] = stats['mp3']['current'][3:].decode('utf-8')

    return stats
